Online-Academy
Look, Read, Understand, Apply

Practical Questions - 2025

Each Question should be Answered and coded like in a given example.
Java Practical Questions
Title: Write a program to swap two numbers using a temporary variable.
Description: This program is written to swap values of two numbers, to swap numbers third variable is used.
        code
class NumSwap{ public static void main(String[] aargs){ int x = 55, y = 66, t; System.out.println("Before Swapping: x: "+x+" y: "+y); t = x; x = y; y = t; System.out.println("After Swapping: x: "+x+" y: "+y); } }
Output: 
        Before Swapping: x: 55 y: 66
        After Swapping: x: 66 y: 55
    
  1. Write a program to swap two numbers using a temporary variable.
  2. Write a program to find the area and perimeter of a rectangle.
  3. Write a program to calculate the simple interest.
  4. Control Statements (if, if-else, switch)
  5. Write a program to check if a number is even or odd.
  6. Write a program to find the largest of three numbers.
  7. Write a program to check whether a character is a vowel or consonant.
  8. This Program checks if a char is vowel or consonant. A char variable is declared and a value is assigned to it. if statement used to check if it is vowel or consonant.

        Code
        We can have class with name main also. 
        class Main {
        public static void main(String[] args) {
          char x = 'a';
          if(x == 'a'||x == 'e'||x == 'i'||x == 'o'||x == 'u'){
              System.out.println("Vowel");
          }else{
              System.out.println("Consonant");
          }
        }
        }
        Output: 
        Vowel
    
  9. Write a program to check if a year is a leap year.
  10. Write a program to print all natural numbers from 1 to 100 using a while loop.
  11. Write a program to print the multiplication table of a given number.
  12. Write a program to find the factorial of a number.
  13. In this program recursive function is defined to find factorial of a number. That function is defined in the same class in which main is defined, and called from main method, So, function is made static.

    Code
    class Factorial {
        public static int fact(int f){
            if(f == 0 || f == 1)
                return 1;
            else
                return (f * fact(f-1));
        }
        public static void main(String[] args) {
        int x = 6;
          System.out.println("Factorial of "+x+ " is: "+fact(x));
        }
    }
    
    Output:
    Factorial of 6 is: 720
  14. Write a program to check whether a number is a prime number.
  15. Write a program to print the Fibonacci series up to n terms.
  16. Write a program to find the largest element in an array.
  17. Write a program to copy all elements from one array to another.
  18. Two integer arrays are created: arr1 and arr2. arr1 is initialized with some values, the arr1 is assigned to arr2. For loop is used to display content of arr2.

    code
        class CopyArray {
        public static void main(String[] args) {
        int[] arr1 = {1,2,33,44,12,32};
        int[] arr2;
        arr2 = arr1;
        for(int i=0;i<arr2.length;i++)
          System.out.println(i+ ": "+arr2[i]);
        }
    }
    
    Output
    0: 1
    1: 2
    2: 33
    3: 44
    4: 12
    5: 32
  19. Write a program to sort an array in ascending order.
  20. Write a program to count the total number of even and odd elements in an array.
  21. Write a program to count the number of vowels in a string.
  22. Write a program to check if a string is a palindrome.
  23. Write a program to reverse a string.
  24. In this program object of StringBuilder class is created, it is mutable, but String is immutable. String is passed to StringBuilder object, reversed method called and then toString method is called and assigned to another string reservedString.

    Code
        class CopyArray {
        public static void main(String[] args) {
            String originalString = "Lhoste";
            StringBuilder stringBuilder = new StringBuilder(originalString);
            String reversedString = stringBuilder.reverse().toString();
            System.out.println("Original String: " + originalString);
            System.out.println("Reversed String: " + reversedString);
            }
        }
    
    Output
    Original String: Lhoste
    Reversed String: etsohL
    
  25. Write a program to compare two strings without using equals() method.
  26. Write a method to calculate the power of a number using recursion.
  27. A private recursive method is written. It takes two parameter, x and y, y is power of y.

    Code:
        class NumPowered {
        private static int powermethod(int x,int y){
            if(y==1)
                return x;
            else{
                return x * powermethod(x,y-1);
            }
        }
        public static void main(String[] args) {
        int p = powermethod(7,4);
        System.out.println("Power: " + p);
        }
    }
    
    Output:

    Power: 2401

  28. Write a method that checks if a number is prime.
  29. Write a method to return the factorial of a given number.
  30. Write a method to find the GCD of two numbers.
  31. Two methods: recursive and non-recursive methods are written to find GCD of two given numbers in this program

    Code
        class CommonDivisor {
        static int a,b;
        private static int nonrecursiveGCD(int a,int b){
             while (b != 0) {
                int temp = b;
                b = a % b;
                a = temp;
            }
            return a; 
        }
        private static int recursiveGCD(int a, int b) {
            if (b == 0)
                return a; // base case
            return recursiveGCD(b, a % b); // recursive step
        }
        public static void main(String[] args) {
        int p = nonrecursiveGCD(96,15);
        System.out.println("Non RecursivePower: " + p);
        int p1 = recursiveGCD(96,15);
        System.out.println("Recursive Power: " + p1);
        }
    }
    
    Output

    Non RecursivePower: 3 Recursive Power: 3

  32. Create a Student class with attributes name, age, and grade. Create objects and display their data.
  33. Create a Calculator class with methods for addition, subtraction, multiplication, and division.
  34. Create a BankAccount class with deposit and withdraw methods.
  35. Create a class Rectangle with method to calculate area and perimeter.
  36. Create a class Animal with a method makeSound(). Inherit it in Dog and Cat classes and override the method.
  37. Create a base class Employee with fields name and salary. Inherit it in Manager class that adds a bonus field.
  38. Create a Shape class with a method area(). Inherit it in Circle and Rectangle, and implement the area calculation in each.
  39. Create a constructor chain using super() in a multilevel inheritance example.
  40. Create a class MathOperations that has overloaded methods for:
  41. Adding two integers
    Adding two doubles
    Adding three integers
    
  42. Write a program to demonstrate method overloading for calculating area of square, rectangle, and triangle.
  43. Create an interface Playable with method play(). Implement it in classes Football and Cricket.
  44. Create an interface Shape with area() and perimeter() methods. Implement it in classes Circle and Rectangle.
  45. Create an interface Vehicle with method start(). Create two classes Car and Bike that implement it.
  46. Write a program to demonstrate try-catch-finally block.
  47. Write a program that handles ArrayIndexOutOfBoundsException.
  48. Write a program that throws a custom exception if age is less than 18 when applying for a license.
  49. Handle multiple exceptions in a single program (ArithmeticException, NullPointerException, etc.)
  50. Create a generic class Box with methods to set and get value.
  51. Create a generic method that prints elements of any type of array.
  52. Create a generic class Calculator that performs basic arithmetic operations.
  53. Demonstrate use of bounded type parameters using generics in a class or method.
  54. Create an abstract class Vehicle with an abstract method move(). Extend it in Car and Bicycle classes.
  55. Use interface and inheritance together in a program involving Person, Student, and Employee.
  56. Create a class that uses method overloading and also implements an interface.
  57. Write a program to take input of a student's name, age, and marks from the user and display them.
  58. Write a program that reads a line of text from the user and counts the number of words.
  59. Write a program to read two integers from the user and perform addition, subtraction, multiplication, and division.
  60. Write a program that takes a string input and checks if it's a palindrome.
  61. Write a program to create a new text file and write a message into it and display back its content in console.
  62. In thin program FileInputStream and FileOutputStream classes are used to read and write to a text file.

    Code
    import java.io.*;
    class WriteFile{
        public static void main(String[] aa){
            FileOutputStream fout;
            try{
                fout = new FileOutputStream("hi.txt");
                String text = "Hello From World, World is deteriorating day by day, and in 2025, Artificial Intelligence is becoming powerful day by day, and already deteriorated world is hampered by AI more.  Humans are become slave of AI, they are ceding to AI. ";
                for(int i=0;i<text.length();i++){
                    fout.write(text.charAt(i));
                }
                fout.close();
            }catch(IOException e){
                System.out.println("Error ! "+e.getMessage());
            }
            FileInputStream fin;
            try{
                fin = new FileInputStream("hi.txt");
                int c;
                while((c = fin.read())!=-1)
                System.out.print((char)c);
                fin.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
    
    Output
    C:\Books\JaVA_IMS\File_prog>javac WriteFile.java
    
    C:\Books\JaVA_IMS\File_prog>java WriteFile
    Hello From World, World is deteriorating day by day, and in 2025, Artificial Intelligence is becoming powerful day by day, and already deteriorated world is hampered by AI more.  Humans are become slave of AI, they are ceding to AI.
    C:\Books\JaVA_IMS\File_prog>
    
    
  63. Write a program to read content from an existing text file and display it on the console.
  64. Write a program to copy content from one file to another.
  65. Write a program to count the number of characters, words, and lines in a text file.
  66. Write a program to append text to an existing file.
  67. Write a program to search for a word in a file and display the number of occurrence of it.
  68. This program uses Scanner object to read a text file. Word to be searched is passed as argumen to main method from console while executing byte code. hasNext() method of scanner object is used to read each word of the file. word to be search is assigned to str variable.

    Code:
            import java.io.File;
        import java.io.FileNotFoundException;
        import java.util.Scanner;
    
        public class ReadWordsScanner {
            public static void main(String[] args) {
                try {
                    File file = new File("hi.txt"); // Replace with your file path
                    Scanner scanner = new Scanner(file);
                    String str = args[0];
                    int count = 0;
                    String word="";
                    while (scanner.hasNext()) { // Checks if there's another token (word)
                        word = scanner.next(); // Reads the next token (word)
                        if(word.equals(str)){
                            ++count;
                        }
                    }
                    
                    System.out.println(str+ " is found!"+ count+" times");
            
                    scanner.close();
                } catch (FileNotFoundException e) {
                    System.err.println("File not found: " + e.getMessage());
                }
            }
        }
    
    Output:
        C:\Books\JaVA_IMS\File_prog>javac ReadWordsScanner.java
    
    C:\Books\JaVA_IMS\File_prog>java ReadWordsScanner world
    world is found!1 times
    
    C:\Books\JaVA_IMS\File_prog>java ReadWordsScanner day
    day is found!2 times
    
    C:\Books\JaVA_IMS\File_prog>
    
  69. Write a program to read a file using FileInputStream and print its contents byte by byte.
  70. Write a program to write byte data into a file using FileOutputStream.
  71. Write a program to copy an image or binary file using byte streams.
  72. Write a program to read a text file using FileReader.
  73. Write a program to write character data into a file using FileWriter.
  74. Create a Student class. Write a program to serialize and deserialize its object.
  75. Write a program that stores an ArrayList of custom objects into a file using serialization.
  76. Write a program using BufferedReader to read data from a text file line by line.
  77. Write a program using BufferedWriter to write multiple lines to a file.
  78. Write a program to read data from a file and display only the lines that contain a specific keyword.
  79. Create a log file system where every user input is stored into a file with timestamps.
  80. Create a simple contact manager that allows users to store and read contact information from a file.
  81. Create a user-defined package mypackage with a class Message that prints "Hello from Package". Access this class from another program. Create two packages: mathutils with a class Calculator having basic operations. app to use Calculator class and perform operations.
  82. Create a package bank with a class Account. Include deposit() and withdraw() methods, then access them from another class using import.
  83. Demonstrate the use of import, import static, and fully qualified class name to access a package member.
  84. Create a class with the same name in two different packages and show how to access both using fully qualified names.
  85. This program uses concept of package. Package is like a folder and is created using Package keyword, must be first statement in the program. In this program two packages: packone and packtwo are created, both have display() method. And a driver class is created in which objects from both packages are created and display method is called.

    package packone;
    public class MyClass {
        public void display() {
            System.out.println("This is packone.MyClass");
        }
    }
    
    package packtwo;
    public class MyClass {
        public void display() {
            System.out.println("This is packtwo.MyClass");
        }
    }
    
    public class TestClass {
        public static void main(String[] args) {
            // Using fully qualified names to avoid conflict
            packone.MyClass obj1 = new packone.MyClass();
            packtwo.MyClass obj2 = new packtwo.MyClass();
    
            obj1.display(); // Output: This is packone.MyClass
            obj2.display(); // Output: This is packtwo.MyClass
        }
    }
    
    
    Compile
    javac packone/MyClass.java packtwo/MyClass.java TestClass.java
    Run
    java TestClass
  86. Write a program to reverse a string using StringBuilder.
  87. Write a program to check whether two strings are anagrams.
  88. Write a program to remove all white spaces from a string.
  89. Write a program to count the number of vowels, consonants, digits, and special characters in a string.
  90. Write a program to check whether a given string is a palindrome or not.
  91. Write a program to convert the first letter of each word in a sentence to uppercase.
  92. Write a program to sort the characters in a string alphabetically.
  93. Compare two strings using: equals() == compareTo()
  94. Write a program to replace all occurrences of a given character in a string.
  95. Write a program to find the longest word in a sentence.

Theory Questions

  1. What is the difference between JDK, JRE, and JVM?
  2. Explain the OOP principles in Java with examples.
  3. What are access modifiers in Java? Explain each with examples.
  4. What is the difference between == and .equals() in Java?
  5. Explain the difference between String, StringBuilder, and StringBuffer.
  6. Explain how for, while, and do-while loops differ.
  7. What is the difference between break and continue?
  8. What is the difference between checked and unchecked exceptions?
  9. Explain the try-catch-finally mechanism with an example.
  10. What is the purpose of throw and throws?
  11. What is method overloading and method overriding? Give examples.
  12. What is the difference between abstract classes and interfaces?
  13. Explain the concept of encapsulation with real-world examples.
  14. What is polymorphism in Java? Give an example.
  15. Describe the lifecycle of a Java object (creation, use, destruction via GC).